﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CarBooker.Infrastructure.DomainBase;
using System.Configuration;
using CarBooker.Infrastructure.EntityFactoryFramework.Configuration;

namespace CarBooker.Infrastructure.EntityFactoryFramework
{
    public class EntityFactoryBuilder
    {
        private static Dictionary<string, object> factories =
            new Dictionary<string, object>();
        public static IEntityFactory<T> BuildFactory<T>()
            where T:EntityBase
        {
            IEntityFactory<T> factory = null;
            string key = typeof(T).Name;
            
            if(EntityFactoryBuilder.factories.ContainsKey(key))
            {
                factory = EntityFactoryBuilder.factories[key] as IEntityFactory<T>;
            }
            else
            {
                EntitySettings settings=
                (EntitySettings)ConfigurationManager.GetSection(EntityMappingConstants.EntityMappingsConfigurationSectionName);
                Type entityFactoryType=
                Type.GetType(settings.EntityMappings[key].EntityFullTypeName);
                factory=Activator.CreateInstance(entityFactoryType) as IEntityFactory<T>;
                EntityFactoryBuilder.factories[key]=factory;
            }
            return factory;
        }
    }
}

